package com.obsidian.service.impl;

import com.obsidian.controller.SigarController;
import com.obsidian.service.ISigarService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.hyperic.jni.ArchNotSupportedException;
import org.hyperic.sigar.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class SigarServiceImpl implements ISigarService {


    private static Logger logger = LoggerFactory.getLogger(SigarServiceImpl.class);

    /**
     * 静态代码块
     */
    static {
        logger.info("***********************加载静态代码块********************");
        try {
            initSigar();
        } catch (IOException e) {
            logger.error("初始化sigar的配置文件失败", e);
        }
    }

    /**
     * 初始化sigar的配置文件
     */
    private static void initSigar() throws IOException {
        logger.info("***********************初始化sigar的配置文件********************");
        SigarLoader loader = new SigarLoader(Sigar.class);
        String lib = null;

        try {
            lib = loader.getLibraryName();
        } catch (ArchNotSupportedException var7) {
            logger.error(var7.getMessage(), var7);
        }
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("classpath:/sigar/" + lib);
        if (resource.exists()) {
            InputStream is = resource.getInputStream();
            File tempDir = FileUtils.getTempDirectory();
            BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(tempDir, lib), false));
            IOUtils.copy(is, os);
            is.close();
            os.close();
            System.setProperty("org.hyperic.sigar.path", tempDir.getCanonicalPath());
        }
        logger.info("***********************初始化sigar的配置文件结束********************");
    }


    @Override
    public CpuInfo[] getCpuInfoList() throws SigarException {
        Sigar sigar = new Sigar();
        CpuInfo[] cpuInfoList = sigar.getCpuInfoList();
        return cpuInfoList;
    }

    @Override
    public CpuPerc[] getCpuPercList() throws SigarException {
        Sigar sigar = new Sigar();
        CpuPerc[] cpuPercList = sigar.getCpuPercList();
        return cpuPercList;
    }

    @Override
    public Mem getMememory() throws SigarException {
        Sigar sigar = new Sigar();
        Mem mem = sigar.getMem();
        return mem;
    }
}
